package com.home.cca.network;

import androidx.annotation.NonNull;

import com.home.cca.model.Order;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.Request;

public class PrintOrdersRequest {
    private static final String URL = ApiClient.getBaseUrl() + "/SupplierManager/PSOrderMgr/PSWaitSendOrderPrint";

    public static String print(List<Order> orders) throws IOException {
        // 构建请求体
        FormBody.Builder formBuilder = new FormBody.Builder();
        formBuilder.add("template", "0");
        for (Order order : orders) {
            formBuilder.add("billIds[]", String.valueOf(order.getId()));
        }
        formBuilder.add("pe", "1");

        Request request = new Request.Builder()
                .url(URL)
                .post(formBuilder.build())
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", ApiClient.getCookie())
                .header("Origin", ApiClient.getBaseUrl())
                .header("Referer", ApiClient.getBaseUrl())
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("docktoken", "")
                .header("key", "15930935383")
                .build();

        String html = ApiClient.execute(request);
        List<String> boxDivList = getBoxDivList(html);
        return toString(boxDivList);
    }

    private static String toString(List<String> boxDivList) {
        StringBuilder sb = new StringBuilder();
        for (String boxDiv : boxDivList) {
            sb.append(addPadding(boxDiv));
        }
        return sb.toString();
    }

    @NonNull
    private static List<String> getBoxDivList(String html) {
        boolean append = false;
        StringBuilder sb = new StringBuilder();

        List<String> boxDivList = new ArrayList<>();
        for (String line : html.split("\n")) {
            if (line.trim().startsWith("<div class=\"boxDiv\">")) {
                append = true;
            }
            if (append) {
                sb.append(line).append("\n");
                if (line.trim().startsWith("</div>")) {
                    boxDivList.add(sb.toString());
                    sb.setLength(0);
                    append = false;
                }
            }
        }
        return boxDivList;
    }

    private static String addPadding(String content) {
        return String.format("<div style=\"padding-left:13mm;padding-top:12mm;\">\n%s</div>\n", content);
    }
}
